package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 查询全部列表
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Spu findById(String id){
        return  spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 修改
     * @param spu
     */
    @Override
    public void update(Spu spu){
        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap){
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size){
        PageHelper.startPage(page,size);
        return (Page<Spu>)spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String,Object> searchMap, int page, int size){
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        return (Page<Spu>)spuMapper.selectByExample(example);
    }

    //根据id查询商品信息
    @Override
    public Goods findGoodsById(String id) {
        Goods goods = new Goods();
        //根据id查询出spu的数据
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //将spu存入goods
        goods.setSpu(spu);
        //根据spu的id查询出sku的信息
        List<Sku> skuList = spuMapper.findSkuById(id);
        //将sku集合的数据存入goods
        goods.setSkuList(skuList);
        return goods;
    }

    //商品审核
    @Override
    public void checkGoods(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);

        if (spu == null){
            throw new RuntimeException("商品不存在");
        }

        if (spu.getIsMarketable().equals("1")){
            throw new RuntimeException("商品已经上架,无需审核");
        }

        if (spu.getIsDelete().equals("1")){
            throw new RuntimeException("商品已经被删除");
        }

        //设置审核状态为1，即审核成功
        spu.setStatus("1");
        //设置上架状态为1，即审核成功直接上架
        spu.setIsMarketable("1");

        spuMapper.updateByPrimaryKeySelective(spu);
    }

    //下架商品
    @Override
    public void downGoods(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);

        if (spu == null){
            throw new RuntimeException("商品不存在");
        }

        if (spu.getIsMarketable().equals("0")){
            throw new RuntimeException("商品未上架");
        }

        if (spu.getIsDelete().equals("1")){
            throw new RuntimeException("商品已经被删除");
        }
        //设置上架状态为0，即下架
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);

    }

    //商品删除（逻辑删除，即改变删除状态为1，但是商品数据还在）
    @Override
    public void delGoods(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null){
            throw new RuntimeException("商品不存在");
        }

        if (spu.getIsMarketable().equals("1")){
            throw new RuntimeException("商品正在上架，无法删除，请先下架");
        }

        if (spu.getIsDelete().equals("1")){
            throw new RuntimeException("商品已经被删除，请勿重复点击");
        }
        //执行逻辑删除操作，即修改删除状态为1
        spu.setIsDelete("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    //商品删除（物理删除，即直接删除商品数据）
    @Override
    public void delete(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null){
            throw new RuntimeException("商品不存在");
        }

        if (spu.getIsDelete().equals("0")){
            throw new RuntimeException("商品未被逻辑删除，无法直接删除数据");
        }

        spuMapper.deleteByPrimaryKey(spu);
    }

    //还原逻辑删除商品（即把删除状态从1改为0）
    @Override
    public void backDel(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null){
            throw new RuntimeException("商品不存在");
        }

        if (spu.getIsDelete().equals("0")){
            throw new RuntimeException("商品未被删除，不需要还原");
        }
        spu.setIsDelete("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    //添加
    @Override
    public void add(Goods goods) {

        //1.添加spu
        Spu spu = goods.getSpu();
            //设置分布式ID
            long nextId = idWorker.nextId();
            spu.setId(String.valueOf(nextId));
        spuMapper.insertSelective(spu);
        //2.添加sku集合
        this.addSkuList(goods);
    }

    //修改商品
    @Override
    public void update(Goods goods) {
        Spu spu = goods.getSpu();
        //更新spu数据
        spuMapper.updateByPrimaryKeySelective(spu);
        //更新sku数据，先删除原来的sku，再使用addSkuList()方法添加修改后的sku
        String spuId = spu.getId();
        skuMapper.deleteSku(spuId);
        this.addSkuList(goods);
    }

    //添加sku集合
    public void addSkuList(Goods goods){

        Spu spu = goods.getSpu();
        //查询分类对象
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
        //查询品牌对象
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
        //设置品牌和分类的关联关系
        CategoryBrand categoryBrand = new CategoryBrand();
        //设置商品分类id
        categoryBrand.setCategoryId(spu.getCategory3Id());
        //设置品牌id
        categoryBrand.setBrandId(spu.getBrandId());
        //查询是否有关联关系，如果没有则添加关联关系，如果有就不用管
        int count = categoryBrandMapper.selectCount(categoryBrand);
        if (count == 0){
            categoryBrandMapper.insert(categoryBrand);
        }

        //1.获取sku集合
        List<Sku> skuList = goods.getSkuList();
        //2.判断sku集合是否为空
        if (skuList != null){
            //遍历sku集合
            for (Sku sku : skuList) {
                //3.设置sku的各个属性值
                //3.1  设置sku的id（使用idWork工具类生成）
                sku.setId(String.valueOf(idWorker.nextId()));
                //3.2  设置sku的name（name由spu的name加上规格spec构成）
                String name = spu.getName();
                Map<String,String> map = JSON.parseObject(sku.getSpec(), Map.class);
                if (map != null && map.size() > 0){
                    for (String value : map.values()) {
                        name +=" "+value;
                    }
                }
                sku.setName(name);
                //3.3  设置sku的规格信息(如果为null就设置为{}，防止空指针异常，如果不为null就不用管)
                if (StringUtil.isEmpty(sku.getSpec())){
                    sku.setSpec("{}");
                }
                //3.4  设置sku的spuId
                sku.setSpuId(spu.getId());
                //3.5  设置sku的商品分类id
                sku.setCategoryId(category.getId());
                //3.6  设置sku的商品分类名称
                sku.setCategoryName(category.getName());
                //3.7  设置sku的品牌名称
                sku.setBrandName(brand.getName());
                //3.8  设置sku的修改和创建时间
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());
                //4.将sku添加到数据库
                skuMapper.insertSelective(sku);
            }
        }
    }

    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andEqualTo("id",searchMap.get("id"));
           	}
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andEqualTo("sn",searchMap.get("sn"));
           	}
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
           	}
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
           	}
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
           	}
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
           	}
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                criteria.andLike("saleService","%"+searchMap.get("saleService")+"%");
           	}
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
           	}
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                criteria.andLike("specItems","%"+searchMap.get("specItems")+"%");
           	}
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                criteria.andLike("paraItems","%"+searchMap.get("paraItems")+"%");
           	}
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                criteria.andEqualTo("isMarketable",searchMap.get("isMarketable"));
           	}
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
           	}
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andEqualTo("isDelete",searchMap.get("isDelete"));
           	}
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andEqualTo("status",searchMap.get("status"));
           	}

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
